import fsPromises from 'fs-promise';
import path from 'path';
import fs from 'fs';

import {Readable} from 'stream';
import {finished} from 'stream/promises';

async function saveToFile(fileSavePath: string, buffer: Buffer) {
    if (fileSavePath && buffer) {
        const filePath = path.join(fileSavePath.replaceAll('\\', '/').replaceAll('//', '/'));
        await fsPromises.ensureDir(path.dirname(filePath));


        // 将 Buffer 转换为可读流
        const bufferStream = Readable.from(buffer, {objectMode: false});

        // 创建可写流并处理写入
        const writeStream = fs.createWriteStream(filePath, {emitClose: true});

        try {
            // 使用 pipeline 管理流，自动处理分块和背压
            await finished(
                bufferStream.pipe(writeStream, {end: true})
            );
        } catch (err: any) {
            fs.rm(filePath, () => {
                console.log('清理未完整写入的文件');
            });
            throw new Error(`写入失败: ${err.message}`);
        }

        fs.writeFileSync(filePath, buffer);
    }
}

export default saveToFile;
